package juc;

/**
 * 模拟cas算法
 *
 * @author liweimin
 * @date 2021/4/23 11:01
 * @since
 */
public class CompareAndSwap {
    private int value = 1;

    //获取内存值
    public synchronized int getValue() {
        return value;
    }

    //比较
    public synchronized int compareAndSwap(int expectedValue, int newValue) {
        int oldValue = value;
        if (oldValue == expectedValue) {
            this.value = newValue;
        }
        return oldValue;
    }

    public synchronized boolean compareAndSet(int expectedValue, int newValue) {
        return compareAndSwap(expectedValue, newValue) == expectedValue;
    }


    public static void main(String[] args) {
        CompareAndSwap compareAndSwap = new CompareAndSwap();
        for (int i = 0; i < 10; i++) {
            new Thread(() -> {
                int value = compareAndSwap.getValue();
                boolean b = compareAndSwap.compareAndSet(value, (int) Math.random() * 100);
                System.out.println(b);
            }).start();
        }
    }
}
